#include <iostream>
#include <pthread.h>
#include <unistd.h>
/*运行结果不一样是两个线程争夺CPU资源的结果*/
using namespace std;

void *thread1(void *ptr)
{
	for(int i = 0;i < 3;i++)
	{
		sleep(1);
		cout<<"This is a pthread1."<<endl;
	}
	
	return 0;
}

void *thread2(void *ptr)
{
	for(int i = 0;i < 3;i++)
	{
		sleep(1);
		cout<<"This is a pthread2."<<endl;
	}
	
	return 0;
}

int main()
{
	pthread_t id1,id2;//线程标识符
	
	/*创建线程（线程标识符指针、线程属性、运行函数的起始地址、运行函数的参数）*/
	int ret = pthread_create(&id1,NULL,thread1,NULL);
	if(ret)
	{
		cout<<"Create pthread1 error!"<<endl;
		return 1;
	}
	ret = pthread_create(&id2,NULL,thread2,NULL);
	if(ret)
	{
		cout<<"Create pthread2 error!"<<endl;
		return 1;
	}
	
	for(int i = 0;i < 3;i++)
	{
		cout<<"This is a main process."<<endl;
		sleep(1);
	}
	/*等待线程结束（被等待的线程标识符、用户定义的指针，存储被等待线程的返回值）*/
	pthread_join(id1,NULL);
	pthread_join(id2,NULL);
	return 0;
}